"""
简历生成器
支持生成Word和PDF格式的简历
"""
import os
import io
import tempfile
import requests
from datetime import datetime
from docx import Document
from docx.shared import Inches, Pt, Cm
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.style import WD_STYLE_TYPE
from docx.enum.table import WD_TABLE_ALIGNMENT
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import inch
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle
from reportlab.lib import colors
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from django.conf import settings
from PIL import Image


class ResumeGenerator:
    """简历生成器"""

    def __init__(self, resume_data, template_style='classic'):
        self.resume_data = resume_data
        self.template_style = template_style
        self.template_config = self._get_template_config(template_style)

    def _get_template_config(self, style):
        """获取模板配置"""
        templates = {
            'classic': {
                'name': '经典商务',
                'colors': {
                    'primary': '#2c3e50',
                    'secondary': '#34495e',
                    'accent': '#3498db'
                },
                'fonts': {
                    'title': ('Arial', 18, True),
                    'heading': ('Arial', 14, True),
                    'body': ('Arial', 11, False)
                },
                'layout': 'single_column'
            },
            'modern': {
                'name': '现代简约',
                'colors': {
                    'primary': '#1a1a1a',
                    'secondary': '#666666',
                    'accent': '#007acc'
                },
                'fonts': {
                    'title': ('Calibri', 20, True),
                    'heading': ('Calibri', 14, True),
                    'body': ('Calibri', 11, False)
                },
                'layout': 'two_column'
            },
            'creative': {
                'name': '创意设计',
                'colors': {
                    'primary': '#e74c3c',
                    'secondary': '#2c3e50',
                    'accent': '#f39c12'
                },
                'fonts': {
                    'title': ('Georgia', 22, True),
                    'heading': ('Georgia', 15, True),
                    'body': ('Georgia', 11, False)
                },
                'layout': 'creative'
            },
            'academic': {
                'name': '学术研究',
                'colors': {
                    'primary': '#2c3e50',
                    'secondary': '#7f8c8d',
                    'accent': '#27ae60'
                },
                'fonts': {
                    'title': ('Times New Roman', 16, True),
                    'heading': ('Times New Roman', 14, True),
                    'body': ('Times New Roman', 12, False)
                },
                'layout': 'academic'
            }
        }
        return templates.get(style, templates['classic'])

    def generate_word(self):
        """生成Word格式简历"""
        import io

        doc = Document()

        # 设置页面边距
        sections = doc.sections
        for section in sections:
            section.top_margin = Inches(0.8)
            section.bottom_margin = Inches(0.8)
            section.left_margin = Inches(1.0)
            section.right_margin = Inches(1.0)

        # 设置自定义样式
        self._setup_styles(doc)

        # 根据模板布局生成内容
        layout = self.template_config['layout']

        if layout == 'two_column':
            self._generate_two_column_layout(doc)
        elif layout == 'creative':
            self._generate_creative_layout(doc)
        elif layout == 'academic':
            self._generate_academic_layout(doc)
        else:
            self._generate_single_column_layout(doc)

        # 保存到内存并返回BytesIO对象
        file_stream = io.BytesIO()
        doc.save(file_stream)
        file_stream.seek(0)
        return file_stream

    def _hex_to_rgb(self, hex_color):
        """将十六进制颜色转换为RGB"""
        from docx.shared import RGBColor
        hex_color = hex_color.lstrip('#')
        return RGBColor(
            int(hex_color[0:2], 16),
            int(hex_color[2:4], 16),
            int(hex_color[4:6], 16)
        )

    def _add_left_column_content(self, cell):
        """添加左列内容"""
        # 基本信息
        if self.resume_data.get('basic_info'):
            self._add_section_to_cell(cell, '基本信息', self.resume_data['basic_info'])

        # 技能
        if self.resume_data.get('skills'):
            self._add_skills_to_cell(cell)

    def _add_right_column_content(self, cell):
        """添加右列内容"""
        # 工作经验
        if self.resume_data.get('work_experience'):
            self._add_work_experience_to_cell(cell)

        # 项目经验
        if self.resume_data.get('projects'):
            self._add_projects_to_cell(cell)

    def _add_section_to_cell(self, cell, title, content):
        """在单元格中添加部分"""
        para = cell.paragraphs[0] if cell.paragraphs else cell.add_paragraph()
        run = para.add_run(title)
        run.font.bold = True
        run.font.size = Pt(self.template_config['fonts']['heading'][1])

        if isinstance(content, dict):
            for key, value in content.items():
                if value:
                    p = cell.add_paragraph(f"{key}: {value}")
                    p.style = 'Normal'
        elif isinstance(content, str):
            p = cell.add_paragraph(content)
            p.style = 'Normal'

    def _add_skills_to_cell(self, cell):
        """在单元格中添加技能"""
        para = cell.add_paragraph()
        run = para.add_run('技能特长')
        run.font.bold = True
        run.font.size = Pt(self.template_config['fonts']['heading'][1])

        for skill in self.resume_data['skills']:
            if skill.get('name'):
                p = cell.add_paragraph(f"• {skill['name']}")
                if skill.get('level'):
                    p.add_run(f" ({skill['level']})")

    def _add_work_experience_to_cell(self, cell):
        """在单元格中添加工作经验"""
        para = cell.add_paragraph()
        run = para.add_run('工作经验')
        run.font.bold = True
        run.font.size = Pt(self.template_config['fonts']['heading'][1])

        for exp in self.resume_data['work_experience']:
            if exp.get('company'):
                p = cell.add_paragraph(f"{exp['company']}")
                p.style = 'Normal'
                if exp.get('position'):
                    p.add_run(f" - {exp['position']}")
                if exp.get('duration'):
                    p.add_run(f" ({exp['duration']})")

    def _add_projects_to_cell(self, cell):
        """在单元格中添加项目经验"""
        para = cell.add_paragraph()
        run = para.add_run('项目经验')
        run.font.bold = True
        run.font.size = Pt(self.template_config['fonts']['heading'][1])

        for project in self.resume_data['projects']:
            if project.get('name'):
                p = cell.add_paragraph(f"• {project['name']}")
                p.style = 'Normal'
                if project.get('description'):
                    desc_p = cell.add_paragraph(f"  {project['description']}")
                    desc_p.style = 'Normal'

    def _add_common_sections(self, doc):
        """添加通用部分"""
        # 自我介绍
        if self.resume_data.get('self_introduction'):
            self._add_section(doc, '自我介绍', self.resume_data['self_introduction'])

        # 教育背景
        if self.resume_data.get('education'):
            self._add_education_section(doc)

        # 工作经验
        if self.resume_data.get('work_experience'):
            self._add_work_experience_section(doc)

        # 项目经验
        if self.resume_data.get('projects'):
            self._add_projects_section(doc)

        # 技能特长
        if self.resume_data.get('skills'):
            self._add_skills_section(doc)

        # 获奖情况
        if self.resume_data.get('awards'):
            self._add_awards_section(doc)

    def _add_section(self, doc, title, content):
        """添加通用部分"""
        heading = doc.add_paragraph(title)
        heading.style = 'Heading 2'

        if isinstance(content, str):
            para = doc.add_paragraph(content)
            para.style = 'Normal'
        elif isinstance(content, dict):
            for key, value in content.items():
                if value:
                    para = doc.add_paragraph(f"{key}: {value}")
                    para.style = 'Normal'

    def _generate_single_column_layout(self, doc):
        """生成单列布局 - 按照需求1调整内容顺序"""
        # 1. 个人简历（标题）
        title = doc.add_paragraph(self.resume_data.get('title', '个人简历'))
        title.style = 'Heading 2'  # 使用二级标题样式（四号黑体居中）

        # 2. 基本信息（包含证件照）
        self._add_basic_info_word(doc)

        # 3. 教育背景
        self._add_education_word(doc)

        # 4. 专业技能
        self._add_skills_word(doc)

        # 5. 项目经验
        self._add_projects_word(doc)

        # 6. 工作经验
        self._add_work_experience_word(doc)

        # 7. 获奖经历
        self._add_awards_word(doc)

        # 8. 自我介绍
        self._add_self_introduction_word(doc)

    def _generate_two_column_layout(self, doc):
        """生成双列布局"""
        # 标题
        title = doc.add_paragraph(self.resume_data.get('title', '个人简历'))
        title.style = 'Title'

        # 创建表格实现双列布局
        table = doc.add_table(rows=1, cols=2)
        table.autofit = False
        table.columns[0].width = Inches(2.5)  # 左列宽度
        table.columns[1].width = Inches(4.0)  # 右列宽度

        left_cell = table.cell(0, 0)
        right_cell = table.cell(0, 1)

        # 左列：基本信息、技能等
        self._add_left_column_content(left_cell)

        # 右列：工作经验、项目经验等
        self._add_right_column_content(right_cell)

    def _generate_creative_layout(self, doc):
        """生成创意布局"""
        # 创意标题样式
        title_para = doc.add_paragraph()
        title_run = title_para.add_run(self.resume_data.get('title', '个人简历'))
        title_run.font.size = Pt(24)
        title_run.font.bold = True
        title_run.font.color.rgb = self._hex_to_rgb(self.template_config['colors']['primary'])
        title_para.alignment = WD_ALIGN_PARAGRAPH.CENTER

        # 添加装饰线
        doc.add_paragraph('─' * 50).alignment = WD_ALIGN_PARAGRAPH.CENTER

        # 基本信息和其他部分
        self._add_basic_info_section(doc)
        self._add_common_sections(doc)

    def _generate_academic_layout(self, doc):
        """生成学术布局"""
        # 学术风格标题
        title = doc.add_paragraph(self.resume_data.get('title', 'Curriculum Vitae'))
        title.style = 'Title'
        title.alignment = WD_ALIGN_PARAGRAPH.CENTER

        # 基本信息和其他部分
        self._add_basic_info_section(doc)
        self._add_common_sections(doc)

    def _add_basic_info_section(self, doc):
        """添加基本信息部分"""
        if self.resume_data.get('basic_info'):
            self._add_basic_info_with_avatar(doc)

    def _add_basic_info_with_avatar(self, doc):
        """添加包含头像的基本信息"""
        basic_info = self.resume_data['basic_info']

        # 创建表格来布局基本信息和头像
        table = doc.add_table(rows=1, cols=2)
        table.autofit = False

        # 设置列宽：左侧信息区域宽，右侧头像区域窄
        table.columns[0].width = Inches(4.5)  # 信息区域
        table.columns[1].width = Inches(1.2)  # 头像区域

        info_cell = table.cell(0, 0)
        avatar_cell = table.cell(0, 1)

        # 添加基本信息到左侧
        self._add_basic_info_content(info_cell, basic_info)

        # 添加头像到右侧
        if self.resume_data.get('avatar_path'):
            self._add_avatar_to_cell(avatar_cell, self.resume_data['avatar_path'])

        # 移除表格边框
        self._remove_table_borders(table)

    def _add_basic_info_content(self, cell, basic_info):
        """在单元格中添加基本信息内容"""
        # 添加标题
        title_para = cell.paragraphs[0]
        title_run = title_para.add_run('基本信息')
        title_run.font.bold = True
        title_run.font.size = Pt(self.template_config['fonts']['heading'][1])

        # 添加信息项
        info_items = [
            ('姓名', basic_info.get('姓名', '')),
            ('手机', basic_info.get('手机', '')),
            ('邮箱', basic_info.get('邮箱', '')),
            ('学校', basic_info.get('学校', '')),
            ('专业', basic_info.get('专业', ''))
        ]

        for label, value in info_items:
            if value:
                para = cell.add_paragraph()
                label_run = para.add_run(f'{label}：')
                label_run.font.bold = True
                value_run = para.add_run(value)
                para.style = 'Normal'

    def _add_avatar_to_cell(self, cell, avatar_path):
        """在单元格中添加头像"""
        try:
            # 清空单元格内容
            cell.paragraphs[0].clear()

            # 添加头像
            para = cell.paragraphs[0]
            para.alignment = WD_ALIGN_PARAGRAPH.CENTER

            # 设置头像尺寸：2.2cm × 3.2cm
            run = para.add_run()
            run.add_picture(avatar_path, width=Inches(0.87), height=Inches(1.26))  # 2.2cm ≈ 0.87inch, 3.2cm ≈ 1.26inch

        except Exception as e:
            print(f"添加头像失败: {e}")
            # 如果添加头像失败，添加占位符
            para = cell.add_paragraph('照片')
            para.alignment = WD_ALIGN_PARAGRAPH.CENTER

    def _remove_table_borders(self, table):
        """移除表格边框"""
        from docx.oxml.shared import qn
        from docx.oxml import parse_xml

        # 设置表格边框为无
        tbl = table._tbl
        tblPr = tbl.tblPr

        # 添加边框设置
        tblBorders = parse_xml(r'<w:tblBorders xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:top w:val="nil"/><w:left w:val="nil"/><w:bottom w:val="nil"/><w:right w:val="nil"/><w:insideH w:val="nil"/><w:insideV w:val="nil"/></w:tblBorders>')
        tblPr.append(tblBorders)

    def _setup_styles(self, doc):
        """设置文档样式 - 根据需求3设置格式要求"""
        from docx.oxml.ns import qn

        # 设置正文样式 - 四号宋体，1.5倍行间距
        try:
            content_style = doc.styles.add_style('ContentStyle', WD_STYLE_TYPE.PARAGRAPH)
        except:
            content_style = doc.styles['ContentStyle']

        content_style.font.name = '宋体'
        content_style.font.size = Pt(14)  # 四号字体约14磅
        content_style.paragraph_format.line_spacing = 1.5  # 1.5倍行间距
        content_style.paragraph_format.space_after = Pt(6)

        # 设置中文字体
        content_style._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体')

        # 设置2级标题样式 - 四号黑体居中
        heading2_style = doc.styles['Heading 2']
        heading2_style.font.name = '黑体'
        heading2_style.font.size = Pt(14)  # 四号字体约14磅
        heading2_style.font.bold = True
        heading2_style.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER  # 居中
        heading2_style.paragraph_format.space_before = Pt(18)
        heading2_style.paragraph_format.space_after = Pt(12)
        heading2_style._element.rPr.rFonts.set(qn('w:eastAsia'), '黑体')
        
        # 设置3级标题样式 - 宋体左对齐
        try:
            heading3_style = doc.styles.add_style('Heading 3', WD_STYLE_TYPE.PARAGRAPH)
        except:
            heading3_style = doc.styles['Heading 3']
            
        heading3_style.font.name = '宋体'
        heading3_style.font.size = Pt(14)  # 四号字体约14磅
        heading3_style.font.bold = True
        heading3_style.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.LEFT  # 左对齐
        heading3_style.paragraph_format.space_before = Pt(18)
        heading3_style.paragraph_format.space_after = Pt(12)
        heading3_style._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体')
    
    def _add_basic_info_word(self, doc):
        """添加基本信息到Word文档 - 使用无边框表格两栏布局，左侧基本信息，右侧证件照"""
        from docx.shared import Inches
        from docx.oxml import OxmlElement
        from docx.oxml.ns import qn

        print("开始添加基本信息到Word文档")
        
        # 检查resume_data是否包含basic_info
        if 'basic_info' not in self.resume_data or not self.resume_data['basic_info']:
            print("警告: resume_data中没有basic_info或为空")
            return
            
        basic_info = self.resume_data['basic_info']
        print(f"基本信息数据: {basic_info}")

        # 3级标题
        section_title = doc.add_paragraph('基本信息')
        section_title.style = 'Heading 3'

        # 创建无边框表格，左侧放置基本信息，右侧放置证件照
        table = doc.add_table(rows=1, cols=2)
        table.alignment = WD_TABLE_ALIGNMENT.CENTER
        
        # 设置列宽
        table.columns[0].width = Cm(13)  # 左侧列宽
        table.columns[1].width = Cm(3.5)  # 右侧列宽
        
        # 获取单元格
        left_cell = table.cell(0, 0)  # 左侧单元格（基本信息）
        right_cell = table.cell(0, 1)  # 右侧单元格（证件照）
        
        # 移除表格边框
        self._remove_table_borders(table)
        
        # 在左侧单元格中添加基本信息
        self._add_basic_info_to_cell(left_cell, basic_info)
        
        # 在右侧单元格中添加证件照
        avatar_url = None
        if basic_info.get('avatar'):
            print(f"找到证件照字段: {basic_info['avatar']}")
            avatar_url = basic_info['avatar']
        elif 'avatar_url' in basic_info and basic_info['avatar_url']:
            print(f"找到avatar_url字段: {basic_info['avatar_url']}")
            avatar_url = basic_info['avatar_url']
        elif 'avatar_path' in self.resume_data and self.resume_data['avatar_path']:
            print(f"在resume_data中找到avatar_path: {self.resume_data['avatar_path']}")
            avatar_url = self.resume_data['avatar_path']
        else:
            print("没有找到证件照字段")
            print(f"resume_data键: {list(self.resume_data.keys())}")
            if 'basic_info' in self.resume_data:
                print(f"basic_info键: {list(self.resume_data['basic_info'].keys())}")
        
        if avatar_url:
            self._add_id_photo_to_cell(right_cell, avatar_url)
        
        # 添加空行
        doc.add_paragraph()

    def _remove_table_borders(self, table):
        """移除表格的所有边框"""
        from docx.oxml import OxmlElement
        from docx.oxml.ns import qn
        
        # 遍历表格中的所有单元格
        for row in table.rows:
            for cell in row.cells:
                # 设置单元格边框为无
                tcPr = cell._element.tcPr
                if not tcPr:
                    tcPr = OxmlElement('w:tcPr')
                    cell._element.append(tcPr)
                
                # 创建边框元素
                tcBorders = OxmlElement('w:tcBorders')
                for border_type in ['top', 'left', 'bottom', 'right']:
                    border = OxmlElement(f'w:{border_type}')
                    border.set(qn('w:val'), 'nil')
                    tcBorders.append(border)
                
                # 替换现有边框或添加新边框
                # 使用命名空间查询
                nsmap = {'w': 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'}
                existing_borders = tcPr.find('.//w:tcBorders', namespaces=nsmap)
                if existing_borders is not None:
                    tcPr.replace(existing_borders, tcBorders)
                else:
                    tcPr.append(tcBorders)
        
        print("已移除表格边框")
    
    def _add_basic_info_to_cell(self, cell, basic_info):
        """在单元格中添加基本信息内容（宋体小四22磅行间距）"""
        from docx.oxml.ns import qn
        
        # 收集基本信息
        info_data = []
        if basic_info.get('name'):
            info_data.append(('姓名', basic_info['name']))
        if basic_info.get('gender'):
            gender_map = {'M': '男', 'F': '女', 'male': '男', 'female': '女'}
            info_data.append(('性别', gender_map.get(basic_info['gender'], basic_info['gender'])))
        if basic_info.get('birth_date'):
            info_data.append(('出生日期', basic_info['birth_date']))
        if basic_info.get('phone'):
            info_data.append(('电话', basic_info['phone']))
        if basic_info.get('email'):
            info_data.append(('邮箱', basic_info['email']))
        if basic_info.get('address'):
            info_data.append(('地址', basic_info['address']))
        if basic_info.get('job_intention'):
            info_data.append(('求职意向', basic_info['job_intention']))
        if basic_info.get('expected_salary'):
            info_data.append(('期望薪资', basic_info['expected_salary']))
        
        # 创建信息段落，每行显示两个信息项
        for i in range(0, len(info_data), 2):
            para = cell.add_paragraph()
            para.paragraph_format.line_spacing = Pt(22)  # 22磅行间距
            
            # 第一个信息项
            if i < len(info_data):
                label, value = info_data[i]
                run1 = para.add_run(f"{label}：{value}")
                run1.font.name = '宋体'
                run1.font.size = Pt(12)  # 小四号
                run1._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体')
                
                # 如果有第二个信息项，添加适当间距
                if i + 1 < len(info_data):
                    para.add_run('    ')  # 添加间距
            
            # 第二个信息项
            if i + 1 < len(info_data):
                label, value = info_data[i + 1]
                run2 = para.add_run(f"{label}：{value}")
                run2.font.name = '宋体'
                run2.font.size = Pt(12)  # 小四号
                run2._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体')
    
    def _add_id_photo_to_cell(self, cell, avatar_url):
        """在单元格中添加证件照（宽2.2cm高3.2cm）"""
        try:
            print(f"开始处理证件照: {avatar_url}")
            
            # 直接处理avatar_url，不通过API下载
            avatar_path = None
            
            # 如果是相对路径，构建完整URL
            if avatar_url and avatar_url.startswith('/'):
                # 本地文件路径
                # 检查并处理路径中可能重复的media部分
                path_parts = avatar_url.lstrip('/').split('/')
                if path_parts and path_parts[0] == 'media':
                    # 如果路径已经包含media前缀，则移除它
                    clean_path = '/'.join(path_parts[1:])
                    print(f"检测到重复的media路径，已移除: {clean_path}")
                else:
                    clean_path = avatar_url.lstrip('/')
                
                full_path = os.path.join(settings.MEDIA_ROOT, clean_path)
                print(f"本地文件路径: {full_path}")
                if os.path.exists(full_path):
                    print(f"文件存在: {full_path}")
                    avatar_path = full_path
                else:
                    print(f"文件不存在: {full_path}")
            elif avatar_url and not avatar_url.startswith('http'):
                # 相对于MEDIA_ROOT的路径
                # 检查并处理路径中可能重复的media部分
                path_parts = avatar_url.split('/')
                if path_parts and path_parts[0] == 'media':
                    # 如果路径已经包含media前缀，则移除它
                    clean_path = '/'.join(path_parts[1:])
                    print(f"检测到相对路径中重复的media，已移除: {clean_path}")
                else:
                    clean_path = avatar_url
                
                full_path = os.path.join(settings.MEDIA_ROOT, clean_path)
                print(f"相对路径: {full_path}")
                if os.path.exists(full_path):
                    print(f"文件存在: {full_path}")
                    avatar_path = full_path
                else:
                    print(f"文件不存在: {full_path}")
            elif avatar_url and avatar_url.startswith('http'):
                # 尝试使用_download_avatar下载
                avatar_path = self._download_avatar(avatar_url)
            
            if avatar_path:
                print(f"成功获取证件照路径: {avatar_path}")
                
                # 创建一个居中对齐的段落来放置证件照
                photo_para = cell.add_paragraph()
                photo_para.alignment = WD_ALIGN_PARAGRAPH.CENTER
                
                # 插入证件照，设置为2.2cm x 3.2cm
                try:
                    run = photo_para.add_run()
                    picture = run.add_picture(avatar_path, width=Cm(2.2), height=Cm(3.2))
                    print(f"成功插入证件照")
                except Exception as pic_error:
                    print(f"插入图片失败: {str(pic_error)}")
                    import traceback
                    print(traceback.format_exc())
                    # 添加占位文本
                    run = photo_para.add_run("证件照")
                    run.font.size = Pt(12)
                
                # 清理临时文件
                if os.path.exists(avatar_path) and avatar_path.startswith(tempfile.gettempdir()):
                    print(f"清理临时文件: {avatar_path}")
                    os.remove(avatar_path)
            else:
                print("未能获取证件照路径")

        except Exception as e:
            print(f"插入证件照失败: {str(e)}")
            import traceback
            print(traceback.format_exc())
    
    def _add_id_photo_absolute(self, doc, avatar_url):
        """添加证件照到文档右侧（直接插入到段落中并右对齐，衬于文字上方）"""
        try:
            print(f"开始处理证件照: {avatar_url}")
            
            # 直接处理avatar_url，不通过API下载
            avatar_path = None
            
            # 如果是相对路径，构建完整URL
            if avatar_url and avatar_url.startswith('/'):
                # 本地文件路径
                # 检查并处理路径中可能重复的media部分
                path_parts = avatar_url.lstrip('/').split('/')
                if path_parts and path_parts[0] == 'media':
                    # 如果路径已经包含media前缀，则移除它
                    clean_path = '/'.join(path_parts[1:])
                    print(f"检测到重复的media路径，已移除: {clean_path}")
                else:
                    clean_path = avatar_url.lstrip('/')
                
                full_path = os.path.join(settings.MEDIA_ROOT, clean_path)
                print(f"本地文件路径: {full_path}")
                if os.path.exists(full_path):
                    print(f"文件存在: {full_path}")
                    avatar_path = full_path
                else:
                    print(f"文件不存在: {full_path}")
            elif avatar_url and not avatar_url.startswith('http'):
                # 相对于MEDIA_ROOT的路径
                # 检查并处理路径中可能重复的media部分
                path_parts = avatar_url.split('/')
                if path_parts and path_parts[0] == 'media':
                    # 如果路径已经包含media前缀，则移除它
                    clean_path = '/'.join(path_parts[1:])
                    print(f"检测到相对路径中重复的media，已移除: {clean_path}")
                else:
                    clean_path = avatar_url
                
                full_path = os.path.join(settings.MEDIA_ROOT, clean_path)
                print(f"相对路径: {full_path}")
                if os.path.exists(full_path):
                    print(f"文件存在: {full_path}")
                    avatar_path = full_path
                else:
                    print(f"文件不存在: {full_path}")
            elif avatar_url and avatar_url.startswith('http'):
                # 尝试使用_download_avatar下载
                avatar_path = self._download_avatar(avatar_url)
            
            if avatar_path:
                print(f"成功获取证件照路径: {avatar_path}")
                
                # 创建一个右对齐的段落来放置证件照
                photo_para = doc.add_paragraph()
                photo_para.alignment = WD_ALIGN_PARAGRAPH.RIGHT
                
                # 插入证件照，设置为3.2cm x 2.2cm，并设置为衬于文字上方
                try:
                    run = photo_para.add_run()
                    picture = run.add_picture(avatar_path, width=Cm(3.2), height=Cm(2.2))
                    
                    # 设置图片为衬于文字上方（behind text）
                    from docx.oxml.ns import qn
                    from docx.oxml import OxmlElement
                    
                    # 获取图片元素
                    pic = run._r.xpath('w:drawing/wp:inline/a:graphic/a:graphicData/pic:pic')[0]
                    
                    # 将inline转换为anchor以支持文字环绕
                    inline = pic.getparent().getparent().getparent()
                    anchor = OxmlElement('wp:anchor')
                    for attr, val in inline.items():
                        anchor.set(attr, val)
                    
                    # 设置必要的属性
                    anchor.set('simplePos', '0')
                    anchor.set('relativeHeight', '0')
                    anchor.set('behindDoc', '1')  # 衬于文字上方
                    anchor.set('locked', '0')
                    anchor.set('layoutInCell', '1')
                    anchor.set('allowOverlap', '1')
                    
                    # 复制inline的内容到anchor
                    for child in inline:
                        anchor.append(child)
                    
                    # 替换inline为anchor
                    inline.getparent().replace(inline, anchor)
                    
                    print(f"成功插入证件照并设置为衬于文字上方")
                except Exception as pic_error:
                    print(f"插入图片失败: {str(pic_error)}")
                    import traceback
                    print(traceback.format_exc())
                    # 添加占位文本
                    run = photo_para.add_run("证件照")
                    run.font.size = Pt(12)
                
                # 清理临时文件
                if os.path.exists(avatar_path) and avatar_path.startswith(tempfile.gettempdir()):
                    print(f"清理临时文件: {avatar_path}")
                    os.remove(avatar_path)
            else:
                print("未能获取证件照路径")

        except Exception as e:
            print(f"插入证件照失败: {str(e)}")
            import traceback
            print(traceback.format_exc())

    def _add_basic_info_content(self, doc, basic_info):
        """添加基本信息内容（纯文字，宋体小四22磅行间距）"""
        from docx.oxml.ns import qn

        # 收集基本信息
        info_data = []
        if basic_info.get('name'):
            info_data.append(('姓名', basic_info['name']))
        if basic_info.get('gender'):
            gender_map = {'M': '男', 'F': '女', 'male': '男', 'female': '女'}
            info_data.append(('性别', gender_map.get(basic_info['gender'], basic_info['gender'])))
        if basic_info.get('birth_date'):
            info_data.append(('出生日期', basic_info['birth_date']))
        if basic_info.get('phone'):
            info_data.append(('电话', basic_info['phone']))
        if basic_info.get('email'):
            info_data.append(('邮箱', basic_info['email']))
        if basic_info.get('address'):
            info_data.append(('地址', basic_info['address']))
        if basic_info.get('job_intention'):
            info_data.append(('求职意向', basic_info['job_intention']))
        if basic_info.get('expected_salary'):
            info_data.append(('期望薪资', basic_info['expected_salary']))

        # 创建信息段落，每行显示两个信息项
        for i in range(0, len(info_data), 2):
            para = doc.add_paragraph()
            para.paragraph_format.line_spacing = Pt(22)  # 22磅行间距

            # 第一个信息项
            if i < len(info_data):
                label, value = info_data[i]
                run1 = para.add_run(f"{label}：{value}")
                run1.font.name = '宋体'
                run1.font.size = Pt(12)  # 小四号
                run1._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体')

                # 如果有第二个信息项，添加适当间距
                if i + 1 < len(info_data):
                    para.add_run('    ')  # 添加间距

            # 第二个信息项
            if i + 1 < len(info_data):
                label, value = info_data[i + 1]
                run2 = para.add_run(f"{label}：{value}")
                run2.font.name = '宋体'
                run2.font.size = Pt(12)  # 小四号
                run2._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体')

        # 添加空行
        doc.add_paragraph()

    def _download_avatar(self, avatar_url):
        """下载头像文件到临时位置"""
        try:
            print(f"尝试下载头像: {avatar_url}")
            
            # 如果是相对路径，构建完整URL
            if avatar_url.startswith('/'):
                # 本地文件路径
                # 检查并处理路径中可能重复的media部分
                path_parts = avatar_url.lstrip('/').split('/')
                if path_parts and path_parts[0] == 'media':
                    # 如果路径已经包含media前缀，则移除它
                    clean_path = '/'.join(path_parts[1:])
                    print(f"检测到重复的media路径，已移除: {clean_path}")
                else:
                    clean_path = avatar_url.lstrip('/')
                
                full_path = os.path.join(settings.MEDIA_ROOT, clean_path)
                print(f"本地文件路径: {full_path}")
                if os.path.exists(full_path):
                    print(f"文件存在: {full_path}")
                    return full_path
                else:
                    print(f"文件不存在: {full_path}")
                    return None
            elif avatar_url.startswith('http'):
                # 网络URL，下载到临时文件
                print(f"下载网络URL: {avatar_url}")
                response = requests.get(avatar_url, timeout=10)
                if response.status_code == 200:
                    # 创建临时文件
                    import tempfile
                    temp_dir = tempfile.gettempdir()
                    file_extension = os.path.splitext(avatar_url)[1] or '.jpg'
                    temp_filename = f"avatar_{datetime.now().strftime('%Y%m%d_%H%M%S')}{file_extension}"
                    temp_path = os.path.join(temp_dir, temp_filename)

                    with open(temp_path, 'wb') as f:
                        f.write(response.content)

                    print(f"下载成功，保存到: {temp_path}")
                    return temp_path
                else:
                    print(f"下载失败，状态码: {response.status_code}")
            else:
                # 相对于MEDIA_ROOT的路径
                full_path = os.path.join(settings.MEDIA_ROOT, avatar_url)
                print(f"相对路径: {full_path}")
                if os.path.exists(full_path):
                    print(f"文件存在: {full_path}")
                    return full_path
                else:
                    print(f"文件不存在: {full_path}")

        except Exception as e:
            print(f"下载头像失败: {str(e)}")
            import traceback
            print(traceback.format_exc())

        return None

    def _add_self_introduction_word(self, doc):
        """添加自我介绍到Word文档 - 正文宋体四号、1.5倍行间距"""
        self_intro = self.resume_data['self_introduction']

        # 3级标题
        section_title = doc.add_paragraph('自我介绍')
        section_title.style = 'Heading 3'

        # 自我介绍内容
        content_para = doc.add_paragraph(self_intro.get('content', ''))
        content_para.style = 'ContentStyle'
    
    def _add_education_word(self, doc):
        """添加教育背景到Word文档 - 正文宋体四号、1.5倍行间距"""
        education_list = self.resume_data['education']

        # 3级标题
        section_title = doc.add_paragraph('教育背景')
        section_title.style = 'Heading 3'

        for edu in education_list:
            # 时间段
            time_period = f"{edu.get('start_date', '')} - "
            if edu.get('is_current'):
                time_period += "至今"
            else:
                time_period += edu.get('end_date', '至今')

            # 学校和专业信息
            school_info = f"{edu.get('school_name', '')}    {edu.get('major', '')}    {edu.get('degree', '')}"

            # 添加时间段
            time_para = doc.add_paragraph(time_period)
            time_para.style = 'ContentStyle'
            time_para.paragraph_format.line_spacing = 1.5

            # 添加学校信息
            school_para = doc.add_paragraph(school_info)
            school_para.style = 'ContentStyle'
            school_para.paragraph_format.line_spacing = 1.5

            # 添加GPA（如果有）
            if edu.get('gpa'):
                gpa_para = doc.add_paragraph(f"GPA：{edu['gpa']}")
                gpa_para.style = 'ContentStyle'
                gpa_para.paragraph_format.line_spacing = 1.5

            # 添加描述（如果有）
            if edu.get('description'):
                desc_para = doc.add_paragraph(f"描述：{edu['description']}")
                desc_para.style = 'ContentStyle'
                desc_para.paragraph_format.line_spacing = 1.5

            # 添加空行分隔
            doc.add_paragraph()
    
    def _add_skills_word(self, doc):
        """添加专业技能到Word文档 - 使用无序列表展示"""
        skills_list = self.resume_data['skills']

        # 3级标题
        section_title = doc.add_paragraph('专业技能')
        section_title.style = 'Heading 3'

        for skill in skills_list:
            skill_text = f"{skill.get('name', '')}"
            if skill.get('level'):
                skill_text += f" - {skill['level']}"
            if skill.get('description'):
                skill_text += f"：{skill['description']}"

            # 创建无序列表项
            skill_para = doc.add_paragraph(skill_text, style='List Bullet')
            skill_para.style = 'ContentStyle'
            # 保持列表格式但应用自定义样式
            skill_para.paragraph_format.line_spacing = Pt(22)
    
    def _add_projects_word(self, doc):
        """添加项目经验到Word文档 - 合理处理项目数据和格式"""
        projects_list = self.resume_data['projects']

        # 3级标题
        section_title = doc.add_paragraph('项目经验')
        section_title.style = 'Heading 3'

        for project in projects_list:
            # 项目名称和时间段
            project_title = f"{project.get('name', '')}"
            if project.get('start_date'):
                time_period = f" ({project['start_date']} - "
                if project.get('is_current'):
                    time_period += "至今)"
                else:
                    time_period += f"{project.get('end_date', '至今')})"
                project_title += time_period

            # 项目标题（加粗）
            title_para = doc.add_paragraph()
            title_para.style = 'ContentStyle'
            title_run = title_para.add_run(project_title)
            title_run.bold = True

            # 所属组织和角色
            if project.get('company_or_organization') or project.get('role'):
                org_role_text = ""
                if project.get('company_or_organization'):
                    org_role_text += f"所属组织：{project['company_or_organization']}"
                if project.get('role'):
                    if org_role_text:
                        org_role_text += f"    担任角色：{project['role']}"
                    else:
                        org_role_text += f"担任角色：{project['role']}"

                org_para = doc.add_paragraph(org_role_text)
                org_para.style = 'ContentStyle'

            # 项目概况
            if project.get('overview'):
                overview_para = doc.add_paragraph(f"项目概况：{project['overview']}")
                overview_para.style = 'ContentStyle'

            # 主要职责
            if project.get('responsibilities'):
                resp_para = doc.add_paragraph(f"主要职责：{project['responsibilities']}")
                resp_para.style = 'ContentStyle'

            # 使用技术
            if project.get('technologies'):
                tech_para = doc.add_paragraph(f"使用技术：{project['technologies']}")
                tech_para.style = 'ContentStyle'

            # 项目成果
            if project.get('achievements'):
                achieve_para = doc.add_paragraph(f"项目成果：{project['achievements']}")
                achieve_para.style = 'ContentStyle'

            # 问题总结
            if project.get('problems_and_summary'):
                summary_para = doc.add_paragraph(f"问题总结：{project['problems_and_summary']}")
                summary_para.style = 'ContentStyle'

            # 项目间添加空行
            doc.add_paragraph()
    
    def _add_work_experience_word(self, doc):
        """添加工作经验到Word文档 - 合理处理工作经验数据和格式"""
        work_list = self.resume_data['work_experience']

        # 3级标题
        section_title = doc.add_paragraph('工作经验')
        section_title.style = 'Heading 3'

        for work in work_list:
            # 公司名称和岗位
            work_title = f"{work.get('company_name', '')} - {work.get('position_name', '')}"
            if work.get('start_date'):
                time_period = f" ({work['start_date']} - "
                if work.get('is_current'):
                    time_period += "至今)"
                else:
                    time_period += f"{work.get('end_date', '至今')})"
                work_title += time_period

            # 工作标题（加粗）
            title_para = doc.add_paragraph()
            title_para.style = 'ContentStyle'
            title_run = title_para.add_run(work_title)
            title_run.bold = True

            # 工作职责
            if work.get('job_responsibilities'):
                resp_para = doc.add_paragraph(f"工作职责：{work['job_responsibilities']}")
                resp_para.style = 'ContentStyle'

            # 工作成果
            if work.get('achievements'):
                achieve_para = doc.add_paragraph(f"工作成果：{work['achievements']}")
                achieve_para.style = 'ContentStyle'

            # 工作经验间添加空行
            doc.add_paragraph()

    def _add_awards_word(self, doc):
        """添加获奖经历到Word文档 - 无序列表展示"""
        awards_list = self.resume_data['awards']

        # 3级标题
        section_title = doc.add_paragraph('获奖经历')
        section_title.style = 'Heading 3'

        for award in awards_list:
            award_text = f"{award.get('award_name', '')}"

            # 添加奖项等级
            if award.get('award_level'):
                level_map = {
                    'school': '校级',
                    'county': '县级',
                    'city': '市级',
                    'province': '省级',
                    'national': '国家级'
                }
                award_text += f" ({level_map.get(award['award_level'], award['award_level'])})"

            # 添加获奖时间
            if award.get('date_received'):
                award_text += f" - {award['date_received']}"

            # 创建无序列表项
            award_para = doc.add_paragraph(award_text, style='List Bullet')
            award_para.style = 'ContentStyle'
            award_para.paragraph_format.line_spacing = Pt(22)

            # 添加奖项描述（如果有）
            if award.get('award_description'):
                desc_para = doc.add_paragraph(f"    {award['award_description']}")
                desc_para.style = 'ContentStyle'
    
    def generate_pdf(self):
        """生成PDF格式简历"""
        buffer = io.BytesIO()
        doc = SimpleDocTemplate(buffer, pagesize=A4, topMargin=0.5*inch, bottomMargin=0.5*inch)
        
        # 创建样式
        styles = getSampleStyleSheet()
        
        # 标题样式
        title_style = ParagraphStyle(
            'CustomTitle',
            parent=styles['Heading1'],
            fontSize=18,
            spaceAfter=12,
            alignment=1,  # 居中
            fontName='Helvetica-Bold'
        )
        
        # 章节标题样式
        section_style = ParagraphStyle(
            'SectionTitle',
            parent=styles['Heading2'],
            fontSize=14,
            spaceBefore=12,
            spaceAfter=6,
            fontName='Helvetica-Bold'
        )
        
        # 正文样式
        content_style = ParagraphStyle(
            'Content',
            parent=styles['Normal'],
            fontSize=11,
            spaceAfter=3,
            fontName='Helvetica'
        )
        
        story = []
        
        # 1. 简历标题
        story.append(Paragraph(self.resume_data.get('title', 'Resume'), title_style))
        story.append(Spacer(1, 12))
        
        # 2. 基本信息
        if self.resume_data.get('basic_info'):
            story.extend(self._add_basic_info_pdf(section_style, content_style))
        
        # 3. 自我介绍
        if self.resume_data.get('self_introduction'):
            story.extend(self._add_self_introduction_pdf(section_style, content_style))
        
        # 4. 教育背景
        if self.resume_data.get('education'):
            story.extend(self._add_education_pdf(section_style, content_style))
        
        # 5. 专业技能
        if self.resume_data.get('skills'):
            story.extend(self._add_skills_pdf(section_style, content_style))
        
        # 6. 项目经验
        if self.resume_data.get('projects'):
            story.extend(self._add_projects_pdf(section_style, content_style))
        
        # 7. 工作经验
        if self.resume_data.get('work_experience'):
            story.extend(self._add_work_experience_pdf(section_style, content_style))
        
        # 8. 获奖经历
        if self.resume_data.get('awards'):
            story.extend(self._add_awards_pdf(section_style, content_style))
        
        doc.build(story)
        buffer.seek(0)
        return buffer
    
    def _add_basic_info_pdf(self, section_style, content_style):
        """添加基本信息到PDF - 包含头像"""
        from reportlab.platypus import Image as RLImage
        from reportlab.lib.units import inch

        basic_info = self.resume_data['basic_info']
        story = []

        story.append(Paragraph('基本信息', section_style))

        # 如果有头像，创建包含头像的表格布局
        if basic_info.get('avatar'):
            try:
                avatar_path = self._download_avatar(basic_info['avatar'])
                if avatar_path:
                    # 创建表格数据：左侧信息，右侧头像
                    info_data = []

                    # 收集基本信息
                    info_text = []
                    if basic_info.get('name'):
                        info_text.append(f"姓名: {basic_info['name']}")
                    if basic_info.get('gender'):
                        gender_map = {'M': '男', 'F': '女', 'male': '男', 'female': '女'}
                        info_text.append(f"性别: {gender_map.get(basic_info['gender'], basic_info['gender'])}")
                    if basic_info.get('phone'):
                        info_text.append(f"电话: {basic_info['phone']}")
                    if basic_info.get('email'):
                        info_text.append(f"邮箱: {basic_info['email']}")
                    if basic_info.get('address'):
                        info_text.append(f"地址: {basic_info['address']}")
                    if basic_info.get('job_intention'):
                        info_text.append(f"求职意向: {basic_info['job_intention']}")

                    # 创建信息段落
                    info_paragraphs = [Paragraph(info, content_style) for info in info_text]

                    # 创建头像图片
                    avatar_img = RLImage(avatar_path, width=1.2*inch, height=1.6*inch)

                    # 创建表格：左侧信息，右侧头像
                    table_data = [
                        [info_paragraphs, avatar_img]
                    ]

                    table = Table(table_data, colWidths=[4*inch, 1.5*inch])
                    table.setStyle(TableStyle([
                        ('VALIGN', (0, 0), (-1, -1), 'TOP'),
                        ('ALIGN', (1, 0), (1, 0), 'CENTER'),
                        ('LEFTPADDING', (0, 0), (-1, -1), 0),
                        ('RIGHTPADDING', (0, 0), (-1, -1), 0),
                        ('TOPPADDING', (0, 0), (-1, -1), 0),
                        ('BOTTOMPADDING', (0, 0), (-1, -1), 0),
                    ]))

                    story.append(table)

                    # 清理临时文件
                    if os.path.exists(avatar_path):
                        os.remove(avatar_path)

                else:
                    # 头像下载失败，只显示文字信息
                    self._add_basic_info_text_only_pdf(story, basic_info, content_style)

            except Exception as e:
                print(f"PDF头像处理失败: {str(e)}")
                # 出错时只显示文字信息
                self._add_basic_info_text_only_pdf(story, basic_info, content_style)
        else:
            # 没有头像，只显示文字信息
            self._add_basic_info_text_only_pdf(story, basic_info, content_style)

        story.append(Spacer(1, 12))
        return story

    def _add_basic_info_text_only_pdf(self, story, basic_info, content_style):
        """添加纯文字基本信息到PDF"""
        info_text = []
        if basic_info.get('name'):
            info_text.append(f"姓名: {basic_info['name']}")
        if basic_info.get('gender'):
            gender_map = {'M': '男', 'F': '女', 'male': '男', 'female': '女'}
            info_text.append(f"性别: {gender_map.get(basic_info['gender'], basic_info['gender'])}")
        if basic_info.get('phone'):
            info_text.append(f"电话: {basic_info['phone']}")
        if basic_info.get('email'):
            info_text.append(f"邮箱: {basic_info['email']}")
        if basic_info.get('address'):
            info_text.append(f"地址: {basic_info['address']}")
        if basic_info.get('job_intention'):
            info_text.append(f"求职意向: {basic_info['job_intention']}")

        for info in info_text:
            story.append(Paragraph(info, content_style))
    
    def _add_self_introduction_pdf(self, section_style, content_style):
        """添加自我介绍到PDF"""
        self_intro = self.resume_data['self_introduction']
        story = []
        
        story.append(Paragraph('Self Introduction', section_style))
        story.append(Paragraph(self_intro.get('content', ''), content_style))
        story.append(Spacer(1, 12))
        
        return story
    
    def _add_education_pdf(self, section_style, content_style):
        """添加教育背景到PDF"""
        education_list = self.resume_data['education']
        story = []
        
        story.append(Paragraph('Education', section_style))
        
        for edu in education_list:
            edu_text = f"{edu.get('start_date', '')} - {edu.get('end_date', 'Present') if not edu.get('is_current') else 'Present'}"
            edu_text += f"<br/>{edu.get('school_name', '')}, {edu.get('major', '')}, {edu.get('degree', '')}"
            
            story.append(Paragraph(edu_text, content_style))
        
        story.append(Spacer(1, 12))
        return story
    
    def _add_skills_pdf(self, section_style, content_style):
        """添加专业技能到PDF"""
        skills_list = self.resume_data['skills']
        story = []
        
        story.append(Paragraph('Skills', section_style))
        
        for skill in skills_list:
            skill_text = f"{skill.get('name', '')}"
            if skill.get('level'):
                skill_text += f" - {skill['level']}"
            
            story.append(Paragraph(skill_text, content_style))
        
        story.append(Spacer(1, 12))
        return story
    
    def _add_projects_pdf(self, section_style, content_style):
        """添加项目经验到PDF"""
        projects_list = self.resume_data['projects']
        story = []
        
        story.append(Paragraph('Projects', section_style))
        
        for project in projects_list:
            project_text = f"<b>{project.get('name', '')}</b>"
            if project.get('start_date'):
                project_text += f" ({project['start_date']} - {project.get('end_date', 'Present') if not project.get('is_current') else 'Present'})"
            
            story.append(Paragraph(project_text, content_style))
            
            if project.get('overview'):
                story.append(Paragraph(f"Overview: {project['overview']}", content_style))
            
            if project.get('responsibilities'):
                story.append(Paragraph(f"Responsibilities: {project['responsibilities']}", content_style))
        
        story.append(Spacer(1, 12))
        return story
    
    def _add_work_experience_pdf(self, section_style, content_style):
        """添加工作经验到PDF"""
        work_list = self.resume_data['work_experience']
        story = []
        
        story.append(Paragraph('Work Experience', section_style))
        
        for work in work_list:
            work_text = f"<b>{work.get('company_name', '')} - {work.get('position_name', '')}</b>"
            if work.get('start_date'):
                work_text += f" ({work['start_date']} - {work.get('end_date', 'Present') if not work.get('is_current') else 'Present'})"
            
            story.append(Paragraph(work_text, content_style))
            
            if work.get('job_responsibilities'):
                story.append(Paragraph(f"Responsibilities: {work['job_responsibilities']}", content_style))
        
        story.append(Spacer(1, 12))
        return story
    
    def _add_awards_pdf(self, section_style, content_style):
        """添加获奖经历到PDF"""
        awards_list = self.resume_data['awards']
        story = []
        
        story.append(Paragraph('Awards', section_style))
        
        for award in awards_list:
            award_text = f"{award.get('award_name', '')}"
            if award.get('date_received'):
                award_text += f" - {award['date_received']}"
            
            story.append(Paragraph(award_text, content_style))
        
        story.append(Spacer(1, 12))
        return story

    def _add_education_section(self, doc):
        """添加教育背景部分"""
        heading = doc.add_paragraph('教育背景')
        heading.style = 'Heading 2'

        education_list = self.resume_data.get('education', [])
        for edu in education_list:
            para = doc.add_paragraph()
            if edu.get('school_name'):
                para.add_run(edu['school_name']).bold = True
            if edu.get('major'):
                para.add_run(f" - {edu['major']}")
            if edu.get('degree'):
                para.add_run(f" ({edu['degree']})")
            if edu.get('start_date') and edu.get('end_date'):
                para.add_run(f" | {edu['start_date']} - {edu['end_date']}")
            para.style = 'Normal'

    def _add_work_experience_section(self, doc):
        """添加工作经验部分"""
        heading = doc.add_paragraph('工作经验')
        heading.style = 'Heading 2'

        work_list = self.resume_data.get('work_experience', [])
        for work in work_list:
            para = doc.add_paragraph()
            if work.get('company_name'):
                para.add_run(work['company_name']).bold = True
            if work.get('position_name'):
                para.add_run(f" - {work['position_name']}")
            if work.get('start_date') and work.get('end_date'):
                para.add_run(f" | {work['start_date']} - {work['end_date']}")
            para.style = 'Normal'

            if work.get('job_responsibilities'):
                desc_para = doc.add_paragraph(work['job_responsibilities'])
                desc_para.style = 'Normal'

    def _add_projects_section(self, doc):
        """添加项目经验部分"""
        heading = doc.add_paragraph('项目经验')
        heading.style = 'Heading 2'

        projects_list = self.resume_data.get('projects', [])
        for project in projects_list:
            para = doc.add_paragraph()
            if project.get('name'):
                para.add_run(project['name']).bold = True
            if project.get('role'):
                para.add_run(f" - {project['role']}")
            if project.get('start_date') and project.get('end_date'):
                para.add_run(f" | {project['start_date']} - {project['end_date']}")
            para.style = 'Normal'

            if project.get('overview'):
                desc_para = doc.add_paragraph(project['overview'])
                desc_para.style = 'Normal'

    def _add_skills_section(self, doc):
        """添加技能特长部分"""
        heading = doc.add_paragraph('技能特长')
        heading.style = 'Heading 2'

        skills_list = self.resume_data.get('skills', [])
        for skill in skills_list:
            para = doc.add_paragraph()
            if skill.get('name'):
                para.add_run(f"• {skill['name']}")
                if skill.get('level'):
                    para.add_run(f" ({skill['level']})")
            para.style = 'Normal'

    def _add_awards_section(self, doc):
        """添加获奖情况部分"""
        heading = doc.add_paragraph('获奖情况')
        heading.style = 'Heading 2'

        awards_list = self.resume_data.get('awards', [])
        for award in awards_list:
            para = doc.add_paragraph()
            if award.get('award_name'):
                para.add_run(f"• {award['award_name']}")
                if award.get('date_received'):
                    para.add_run(f" - {award['date_received']}")
            para.style = 'Normal'
